package components.custom
{
	import com.adobe.utils.AGALMiniAssembler;
	
	import flash.display.Sprite;
	import flash.display.Stage3D;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DProgramType;
	import flash.display3D.Context3DVertexBufferFormat;
	import flash.display3D.IndexBuffer3D;
	import flash.display3D.Program3D;
	import flash.display3D.VertexBuffer3D;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	
	import framework.Message;
	
	public class ExtendSprite extends Sprite
	{
		public function ExtendSprite()
		{
			super();
			addEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
		}
		
		private function addToStageHandler(p_evt:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, addToStageHandler);
			//检测是否支持3d渲染
			if(stage.stage3Ds.length > 0){
				var sd:Stage3D = stage.stage3Ds[0];
				sd.addEventListener(Event.CONTEXT3D_CREATE, create3dHandler);
				sd.addEventListener(ErrorEvent.ERROR, createFaildHandler);
				sd.requestContext3D();
			}
		}
		
		private function create3dHandler(p_evt:Event):void
		{
			var sd:Stage3D = p_evt.target as Stage3D;
			var ct:Context3D = sd.context3D;
			ct.configureBackBuffer(300, 300, 0, true);
			Message.alert(ct.driverInfo);
			
			var triData:Vector.<Number> = Vector.<Number>([
				0, 1, 0, 0, 1,
				1, 0, 0, 1, 0,
				0, 0, 1, 0, 0
			]);
			var vb:VertexBuffer3D = ct.createVertexBuffer(triData.length/5, 5);
			vb.uploadFromVector(triData, 0, triData.length/5);
			
			var indexData:Vector.<uint> = Vector.<uint>([
				0, 1, 2
			]);
			var ib:IndexBuffer3D = ct.createIndexBuffer(indexData.length);
			ib.uploadFromVector(indexData, 0, indexData.length);
			//AGAL
			var vagalcode:String = "mov op, va0\n" + "mov v0, va1";
			var vagal:AGALMiniAssembler = new AGALMiniAssembler();
			vagal.assemble(Context3DProgramType.VERTEX, vagalcode);
			var fagalcode:String = "mov oc, v0";
			var fagal:AGALMiniAssembler = new AGALMiniAssembler();
			fagal.assemble(Context3DProgramType.FRAGMENT, fagalcode);
			var pm:Program3D = ct.createProgram();
			pm.upload(vagal.agalcode, fagal.agalcode);
			ct.clear(0, 0, 0);
			ct.setVertexBufferAt(0, vb, 0, Context3DVertexBufferFormat.FLOAT_2);
			ct.setVertexBufferAt(1, vb, 2, Context3DVertexBufferFormat.FLOAT_3);
			ct.setProgram(pm);
			ct.drawTriangles(ib);
			ct.present();
		}
		
		private function createFaildHandler(p_evt:ErrorEvent):void
		{
			Message.alert("error");
		}
	}
}